package com.baicai.qqlogindemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Create By：bai_cai，on 2019/1/9
 * God bless my code!
 */
public class SDCardDemoActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "SDCardDemoActivity";
    private Button mWriteDataBtn;
    private Button mCheckSdCard;
    private Button mGetSdFreeBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sd_card);

        initView();
        initListener();
    }

    private void initListener() {
        mWriteDataBtn.setOnClickListener(this);
        mCheckSdCard.setOnClickListener(this);
        mGetSdFreeBtn.setOnClickListener(this);
    }

    private void initView() {
        mWriteDataBtn = this.findViewById(R.id.write_data_to_sd_card_btn);
        mCheckSdCard = this.findViewById(R.id.check_sd_card_btn);
        mGetSdFreeBtn = this.findViewById(R.id.get_sd_card_free_size_btn);
    }

    @Override
    public void onClick(View v) {
        if (v == mWriteDataBtn) {
            File storageDirectory = Environment.getExternalStorageDirectory();
            Log.d(TAG, "sd == " + storageDirectory);
            // 写数据到sd
            File file = new File(storageDirectory, "info.txt");

            try {
                FileOutputStream fos = new FileOutputStream(file);
                // 以特定的方式存储账号和密码
                fos.write(("bai").getBytes());
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (v == mCheckSdCard) {
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                Log.d(TAG, "SD 已经挂载");
            } else if (state.equals(Environment.MEDIA_REMOVED)) {
                Log.d(TAG, "SD 卸载");
            }
        } else if (v == mGetSdFreeBtn) {
            File exFile = Environment.getExternalStorageDirectory();
            Log.d(TAG, "Ext-File_Path == " + exFile);
            long freeSpace = exFile.getFreeSpace();
            // 把lang类型转化为存储类型
            String Size_Text = Formatter.formatFileSize(this, freeSpace);
            Log.d(TAG, "SD free == " + Size_Text);

        }
    }
}

